package cn.gzsf.springboot02.controller;

import cn.gzsf.springboot02.entity.User;
import cn.gzsf.springboot02.utils.DBUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

@Controller//标记此类为控制类
public class UserController {

    @ResponseBody//以字符串的形式响应给客户端
    @RequestMapping("/reg")//参数和前端的路径一致，标志由该方法处理请求
    public String reg(User user){
        //输出参数的快捷键 soutp
        System.out.println("user = " + user);
        try {
            Connection conn = DBUtils.getConn();
            String sql = "select id from user where username=?";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1,user.getUsername());
            ResultSet rs = ps.executeQuery();
            if(rs.next()){
                return "用户名已存在!";
            }
            String insertSql = "insert into user values(null,?,?,?,?)";
            PreparedStatement insertPs = conn.prepareStatement(insertSql);
            insertPs.setString(1,user.getUsername());
            insertPs.setString(2, user.getPassword());
            insertPs.setString(3, user.getNick());
            insertPs.setInt(4,user.getAge());
            insertPs.executeUpdate();
        }catch (Exception e){
            e.printStackTrace();
        }
        return "注册成功";
    }

    @ResponseBody
    @RequestMapping("/login")
    public String login(User user){
        System.out.println("user = " + user);
        try {
            Connection conn = DBUtils.getConn();//获取连接
            String sql = "select password from user where username=?";
            PreparedStatement ps = conn.prepareStatement(sql);//获取传输器
            ps.setString(1,user.getUsername());//设置参数
            ResultSet rs = ps.executeQuery();//执行查询
            if(rs.next()){//根据用户名，如果查到了
                String pw = rs.getString(1);//获取密码
                if(pw.equals(user.getPassword())){//数据库中的密码和用户输入的密码对比
                    return "登录成功";
                }else {
                    return "密码错误";
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return "用户名不存在";
    }

}
